using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework.Graphics;
using Meat.Resources;
using Microsoft.Xna.Framework.Content;

namespace Meat.Rendering
{
    public class VertexBufferResource<T> : ICustomResourceType, IVertexResource where T : struct, IVertexType
    {
        List<T> m_Vertices;
        VertexBuffer m_Buffer;
        int m_Count;
        PrimitiveType m_Type;

        public int StartIndex
        { get; set; }

        public int PrimitiveCount
        { get { return m_Count; } }

        public PrimitiveType PrimitiveType
        { get { return m_Type; } }

        public VertexBuffer Buffer
        { get { return m_Buffer; } }

        public VertexBufferResource(List<T> vertices, int primitiveCount, PrimitiveType primitiveType)
        {
            m_Vertices = vertices;
            m_Count = primitiveCount;
            m_Type = primitiveType;
        }

        public void Load(ContentManager content, GraphicsDevice device)
        {
            m_Buffer = new VertexBuffer(device, typeof(T), m_Vertices.Count, BufferUsage.WriteOnly);
            m_Buffer.SetData<T>(m_Vertices.ToArray());
        }

        public void Unload()
        {
            m_Buffer.Dispose();
        }

        public void PreDraw(GraphicsDevice device)
        {
            device.SetVertexBuffer(Buffer);
        }

        public void Draw(GraphicsDevice device)
        {
            device.DrawPrimitives(PrimitiveType, StartIndex, PrimitiveCount);
        }
    }
}
